package com.itheima.putige.putige.common;

import com.itheima.putige.putige.utils.EmailUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.sql.SQLIntegrityConstraintViolationException;

/**
* Description: 全局异常处理
* @author: zjf95
* @date: 2022/3/1 19:23
* @param:
* @return:
*/
@Slf4j
@RestControllerAdvice
@ResponseBody// 将方法的返回值 R 对象转换为json格式的数据, 响应给页面;
@ControllerAdvice(annotations ={ RestController.class, Controller.class})//指定拦截那些类型的控制器;
public class GlobalExceptionHandler {
    @Autowired
    EmailUtils emailUtils;
    @Value("${reggie.email}")
    private String toEmail;

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {

        log.error(ex.getMessage());

        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());

        return R.error(ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R<String> FileNotFoundException(Exception ex){
        if (ex.getCause().getMessage().isEmpty()){
            emailUtils.sendErrorEmail(ex.getCause().getMessage());
        }
        log.error(StringUtils.isEmpty(ex.getMessage()) ? ex.getCause().getMessage() : ex.getMessage());
        return R.error("网络异常");
    }
}
